require "Common/define"
require "Logic/Config"
require "Common/functions"

RedDotsHeroManorHandler ={}
local this = RedDotsHeroManorHandler

function RedDotsHeroManorHandler.init()
    CloseEvent(Config.EventType.FreshManorInfo,this.update);
    CloseEvent(Config.EventType.FreshManorUnlock,this.update);
    CloseEvent(Config.EventType.Fresh_Bag,this.update);
    ListenEvent(Config.EventType.FreshManorInfo,this.update);
    ListenEvent(Config.EventType.FreshManorUnlock,this.update);
    ListenEvent(Config.EventType.Fresh_Bag,this.update);
    return this
end

function RedDotsHeroManorHandler.getFlag()
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroManor,false) then
        return Config.RedDotsFlagState.None;
    end

    local cityCfg = logicMgr.HeroManorManager.getCityModelData();
    local heroQualityLimit = 999;
    for k, v in pairs(cityCfg) do
        local manorInfo = logicMgr.HeroManorManager.getManorInfo(1, v.f_Id);
        if manorInfo == nil then
            if v.f_Free ~= nil and v.f_Free == 1 then
                return Config.RedDotsFlagState.Needful;
            else
                local costItems = decodeJsonStrToTabel(v.f_UnlockCost);
                local flag = true;
                for lk, lv in pairs(costItems) do
                    local mun = logicMgr.ItemManager.getBagNumByTableID(tonumber(lv[1]));
                    if mun < tonumber(lv[2]) then
                        flag = false;
                        break;
                    end
                end
                if flag then
                    return Config.RedDotsFlagState.Needful;
                end
            end
        else
            if manorInfo.masterId == nil or tonumber(manorInfo.masterId) == 0 then
                if v.f_HeroQualityLimit < heroQualityLimit then
                    heroQualityLimit = v.f_HeroQualityLimit;
                end
            end
        end
    end

    local tableHeros = logicMgr.HeroManager.getOwnerHeroList();
    table.sort(tableHeros, logicMgr.HeroManager.sortHeroWithQuality);
    for i = 1, #tableHeros do
        if tableHeros[i].star >= heroQualityLimit then
            local partnerId = tableHeros[i].partnerId;
            if not logicMgr.HeroManorManager.isManorMaster(partnerId) and not logicMgr.HeroManorManager.isManorGuest(partnerId) then
                return Config.RedDotsFlagState.Needful;
            end
        else
            break;
        end
    end
    return Config.RedDotsFlagState.None
end

function RedDotsHeroManorHandler.update()
    RedDotsManager.addBroadcast(Config.RedDotsType.HeroManor);
end